package com.jbt.mds.obdsdk

import com.jbt.mds.obdsdk.extension.SPUtils
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.builder.GetBuilder
import com.zhy.http.okhttp.builder.PostFormBuilder
import com.zhy.http.okhttp.callback.StringCallback
import java.io.File
import java.util.concurrent.TimeUnit


class HttpUtil() {
    companion object {
        const val BASE_URL = "http://115.153.96.26:10061"
    }

    init {
        OkHttpUtils.getInstance().okHttpClient.newBuilder()
            .connectTimeout(10000L, TimeUnit.MILLISECONDS)
            .readTimeout(10000L, TimeUnit.MILLISECONDS)
            .writeTimeout(15 * 1000L, TimeUnit.MILLISECONDS)
            .build()
    }

    //封装请求
    fun postRequest(url: String?, params: Map<String?, String?>?, callback: StringCallback?) {
        OkHttpUtils.post()
            .url(url)
            .params(params)
            .build()
            .execute(callback)
    }

    //上传文件
    fun postFileRequest(
        url: String?,
        file: File,
        callback: StringCallback?
    ) {
        // 检查文件是否存在且可读
        if (!file.exists() || !file.canRead()) {
            callback?.onError(null, Exception("文件不存在或无法读取: ${file.absolutePath}"), 0)
            return
        }
        
        OkHttpUtils.post()
            .url(url)
            .addFile("file", file.name, file)
            .addHeader("Authorization",
                "Bearer " + SPUtils.getString("token", "")
            )
            .build()
            .execute(callback)
    }
}